#pragma semicolon 1

#include <sourcemod>
#include <geoip>
#include <sdktools>
#undef REQUIRE_PLUGIN
#include <autoupdate> 

#define PLUGIN_VERSION "0.1"

new Handle:cmute_mode;
new Handle:cmute_countries;
new Handle:cmute_msg;

new String:country[45];

public Plugin:myinfo =
{
	name = "Country Mute",
	author = "Dragon",
	description = "Mutes Players from an specific Country.",
	version = PLUGIN_VERSION,
	url = "http://GameMods.org"
};

public OnPluginStart()
{
	CreateConVar("sm_cmute_version", PLUGIN_VERSION, "", FCVAR_PLUGIN | FCVAR_REPLICATED | FCVAR_NOTIFY);
	cmute_mode = CreateConVar("sm_cmute_mode", "1", "", FCVAR_PLUGIN);
	cmute_countries = CreateConVar("sm_cmute_countries", "DE", "", FCVAR_PLUGIN);
	cmute_msg = CreateConVar("sm_cmute_msg", "%s (%s) was muted automatically.", "", FCVAR_PLUGIN);
}

public OnAllPluginsLoaded() {
    if(LibraryExists("pluginautoupdate")) {
        // only register myself if the autoupdater is loaded
        // AutoUpdate_AddPlugin(const String:url[], const String:file[], const String:version[])
        AutoUpdate_AddPlugin("countrymute.googlecode.com", "/svn/version.xml", PLUGIN_VERSION);
    }
}

public OnPluginEnd() {
    if(LibraryExists("pluginautoupdate")) {
        // I don't need updating anymore
        // AutoUpdate_RemovePlugin(Handle:plugin=INVALID_HANDLE) - don't specifiy plugin to remove calling plugin
        AutoUpdate_RemovePlugin();
    }
}

public bool:OnClientConnect(client, String:rejectmsg[], maxlen)
{
	new String:ip[16];
	new String:code2[3];

	GetClientIP(client, ip, sizeof(ip));
	GeoipCode2(ip, code2);
	GeoipCountry(ip, country, sizeof(country));
	
	if(Reject(code2))
	{
		CreateTimer(15.0, cfTimer, client);
	}
	
	return true;
}

public bool:Reject(const String:code2[])
{
	if(StrEqual("", code2))
		return false;
		
	new String:str[255];
	new String:arr[100][3];
	
	GetConVarString(cmute_countries, str, 255);
	
	new total = ExplodeString(str, " ", arr, 100, 3);
	if(total == 0) strcopy(arr[total++], 3, str);
	
	if(GetConVarInt(cmute_mode) == 2)
	{
		for(new i = 0; i < total; i++)
		{
			if(StrEqual(arr[i], code2))
				return true;
		}
	}
	else
	{
		new bool:reject = true;
		
		for(new i = 0; i < total; i++)
		{
			if(StrEqual(arr[i], code2))
				reject = false;
		}
		
		return reject;
	}

	return false;
}

public Action:cfTimer(Handle:timer, any:client)
{
	if (IsClientInGame(client))
	{
	
		new String:name[32];
		new String:rejectmsg[255];
		GetClientName(client, name, 32);
		GetConVarString(cmute_msg, rejectmsg, 255);

		Format(rejectmsg, 255, rejectmsg, name, country);

		SetClientListeningFlags(client, VOICE_MUTED);
	
		PrintToChatAll(rejectmsg);

	}
	else if (IsClientConnected(client))
	{
		CreateTimer(15.0, cfTimer, client);
	}
}
